package net.neptech.service.impl;

import net.neptech.model.schedule.ScheShift;
import net.neptech.repository.ScheShiftRepository;
import net.neptech.service.ScheShiftService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Author HuangZhengmin
 * @desc
 * @Date 2025/8/13 15:30
 * @Version 1.0
 */
@Service
public class ScheShiftServiceImpl implements ScheShiftService {

  @Autowired
  private ScheShiftRepository scheShiftRepository;

  @Override
  public Page<ScheShift> getShiftByName(String shiftName,Long deptId, Integer status, int page, int size) {
    Pageable pageable = PageRequest.of(page, size);
    // 处理shiftName为null的情况（可选参数）
    if (shiftName == null) {
      shiftName = "";  // 设为空字符串，匹配Containing查询
    }
    return scheShiftRepository.findByShiftNameContainingAndDeptIdAndStatus(shiftName,deptId,status, pageable);
  }

  @Override
  public void addScheShift(ScheShift scheShift) {
    //设置创建时间
    if(scheShift.getCreateTime() == null){
      scheShift.setCreateTime(new Date());
    }
    scheShiftRepository.save(scheShift);
  }

  @Override
  public void updateScheShift(ScheShift scheShift) {
    //先查询再修改
    //1.先查询现有实体
    ScheShift existScheShift = scheShiftRepository.findById(scheShift.getShiftId())
            .orElseThrow(()-> new RuntimeException("未找到该班次"));
    //2.更新字段
    existScheShift.setShiftName(scheShift.getShiftName());
    existScheShift.setStartTime(scheShift.getStartTime());
    existScheShift.setEndTime(scheShift.getEndTime());
    existScheShift.setWorkingHours(scheShift.getWorkingHours());
    existScheShift.setStatus(scheShift.getStatus());
    existScheShift.setDeptId(scheShift.getDeptId());
    existScheShift.setUpdateTime(new Date()); // 更新时间

    //3.保存修改后的实体
    scheShiftRepository.save(existScheShift);
  }

  @Override
  public void deleteScheShift(Long id) {
    //先查询再删除 逻辑删除
    ScheShift existScheShift = scheShiftRepository.findById(id)
            .orElseThrow(()-> new RuntimeException("未找到该班次"));
    existScheShift.setStatus(0); // 逻辑删除，将状态改为0-未启用
    scheShiftRepository.save(existScheShift); //  保存修改后的实体
  }

  @Override
  public List<ScheShift> getShiftByDeptId(Long id, Integer status) {
    return scheShiftRepository.findByDeptIdAndStatus(id, status);
  }
}
